# This script works with run_simulation.slurm to execute a single simulation from a slurm array.
## Usage: Rscript run_simulation.R <slurm_array_id>

# GLOBAL VARIABLES
N_SIMS_PER_DESIGN <- 100 # Controls how many iterations we do per design
DEV <- FALSE

# Source simulation_utils
source("simulation_utils.R")

main <- function(slurm_array_id){
    src_data <- load_data(dev=DEV)
    # Define out file
    out_file <- paste0("results/sim_final/", sprintf("%03d", slurm_array_id), ".rds")
    ## Check if exists; if so then exit:
    if (file.exists(out_file)) {
        print(paste("File exists:", out_file))
        return()
    }

    ## Common to all simulations
    fml <- formula("violence ~ sign + photo + fire + police + children + group_20 + flag + night + shouting")
    surrogate_var <- "fire"
    estimator_name <- "lm"


    ## Design grid
    design_grid <- expand.grid(
        n_label = c(100, 250, 500, 750, 1000, 2000),
        gs_acc = c(0.5, 0.75, 0.9, 0.95, 0.99, 1.0),
        q_acc = c(0.5, 0.75, 0.9, 0.95, 0.99, 1.0)
    )
    design <- design_grid[slurm_array_id,]
    print(design)
    gs_error_func <- function(arr){random_binary_error(arr, design$gs_acc)}
    q_error_func <- function(arr){random_binary_error(arr, design$q_acc)}

    ## Run simulation
    sim_result <- repeat_simulation(
        src_data = src_data,
        fml = fml,
        surrogate_var = surrogate_var,
        n_label = design$n_label,
        estimator_name = estimator_name,
        q_error_func = q_error_func,
        gs_error_func = gs_error_func,
        n_sims = N_SIMS_PER_DESIGN
    )

    ## Save results
    saveRDS(sim_result, file=out_file)
}

# Run main
main(slurm_array_id=as.numeric(commandArgs(trailingOnly=TRUE)[1]))
